/**
 * SEVAS - Swiss Electronic Vaccination Advisor Service / Agile Development
 *
 * $Id: Vaccination.java 41 2010-08-24 03:15:52Z zimmr7@bfh.ch $
 */
package ch.bfh.sevas;

import java.util.Date;
import java.util.List;
import javax.swing.table.AbstractTableModel;

public class VaccinationsScheduleModel extends AbstractTableModel {

    private Controller controller;
    private Patient patient;
    private BaseVaccinationCatalog catalog;
    private List<String> vaccinationAges;

    public VaccinationsScheduleModel(Patient patient, Controller controller) {
        this.patient = patient;
        this.catalog = BaseVaccinationCatalog.getFilledBaseVaccineCatalog();
        this.vaccinationAges = Age.getElapsedVaccinationAges(new Age(5000));
        this.controller = controller;
    }

    public int getRowCount() {
        int rowcount = Age.vaccinationAges.size();
        return rowcount;
    }

    public int getColumnCount() {
        int columncount = catalog.getAllVaccinations().size() + 1;
        return columncount;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        String value = "";
        String vaccinationAge = vaccinationAges.get(rowIndex);

        if (columnIndex == 0) {
            value = Age.getLongVaccinationAge(vaccinationAge);
        } else {
            RecommendedBaseVaccination recVacc = catalog.getAllVaccinations().get(columnIndex - 1);

            if (recVacc.getVaccinationAges().contains(vaccinationAge)) {
                value = evaluateVaccincationStatus(recVacc.getCode(), vaccinationAge);
                return new VaccinationScheduleEntry(value, vaccinationAge, recVacc);
            }
        }
        return value;
    }

    public RecommendedBaseVaccination getObjectAt(int rowIndex, int columnIndex) {
        RecommendedBaseVaccination object = null;
        if (columnIndex > 0) {
            object = catalog.getAllVaccinations().get(columnIndex - 1);
        }
        return object;
    }

    @Override
    public String getColumnName(int columnIndex) {
        if (columnIndex == 0) {
            return "Age";
        } else {
            return catalog.getAllVaccinations().get(columnIndex - 1).getCode();
        }
    }

    private String evaluateVaccincationStatus(String code, String vaccinationAge) {
        String result = code;
        Age patientAge = new Age(patient.getDateOfBirth(), new Date());
        if (Age.getElapsedVaccinationAges(patientAge).contains(vaccinationAge)) {
            result = "PENDING";
        }

        for (Vaccination vacc : patient.getVaccinations()) {
            if (vacc.getCode().equals(code) && vacc.getVaccinationAge().equals(vaccinationAge)) {
                result = "DONE";
                break;
            }
        }
        return result;
    }
}